<template>
    <Head>
        <Title>{{ exams.topic.title }}</Title>
        <Meta name="description" :content="exams.topic.description" />
    </Head>
    <div v-if="!exams || !exams.topic"
        class="w-full h-full flex items-center justify-center bg-gradient-to-b from-blue-200 via-blue-200 to-blue-100">
        <h1>没有此活动</h1>
    </div>
    <div v-else-if="!agree"
        class="w-full h-full flex flex-col justify-between bg-gradient-to-b from-blue-200 via-blue-200 to-blue-100">
        <h1 class="text-4xl font-black text-blue-800 text-center px-6 pt-6">{{ exams.topic.title }}</h1>
        <!-- <p class="bg-[#e2ecf0ed] text-slate-500 p-6 rounded leading-relaxed text-justify">{{ exams.topic.description }}</p> -->
        <div class="bg-[#e2ecf0ed] text-slate-500 mx-5 p-6 rounded-lg leading-relaxed text-justify">
            <p><span class="text-slate-600">【答题规则】</span>请如实填写您的信息，以便获奖后能联系到您；本次答题为随机组卷，系统随机抽取 <span class="text-orange-600">{{ exams.topic.quantity }}</span> 道题，答题限时 <span class="text-orange-600">{{ exams.topic.limit }}</span> 秒，超时自动交卷；交卷后显示得分，并可查看本次答题记录。</p>
        </div>

        <el-form ref="ruleFormRef" :model="userForm" status-icon :rules="rules" label-width="80px" class="mx-10">
            <el-form-item label="姓名" prop="nickname">
                <el-input v-model="userForm.nickname" size="large" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input v-model="userForm.phone" size="large" />
            </el-form-item>
            <el-form-item label="单位" prop="company">
                <el-input v-model="userForm.company" size="large" autocomplete="off" />
            </el-form-item>
            <el-form-item class="text-center">
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                <el-button type="primary" @click="agreeHandler(ruleFormRef)">进入答题</el-button>
            </el-form-item>
        </el-form>
        <p class="text-center text-slate-400 leading-relaxed">甘肃省司法厅&copy;版权所有<br>中国甘肃网技术支持</p>
    </div>
    <div v-else class="w-full h-full flex flex-col align-center justify-between">
        <h2 class="bg-blue-300 px-5 py-3 flex items-center justify-between">
            <p class="text-slate-600">答题进度：<span class="text-3xl text-orange-500">{{ curIdx + 1 }}</span>/{{
                exams.options?.length }}</p>
            <p class="text-slate-600">答题时间：<span class="text-3xl text-orange-500">{{ limit }}</span></p>
        </h2>
        <h3 class="p-3 text-xl leading-relaxed"><span>{{ curIdx + 1 }}</span>. 【{{ !exams.options[curIdx]?.C
            ? '判断题' : (exams.options[curIdx]?.answer?.length == 1
                ? '单选题' : '多选题') }}】{{
            exams.options[curIdx]?.title }}</h3>
        <template v-if="exams.options[curIdx]?.answer?.length == 1">
            <el-radio-group v-model="selOpt">
                <template v-for="opt in optArr">
                    <el-radio v-if="exams.options[curIdx]?.[opt]" :label="opt" size="large" border class="w-full">
                        <p class="text-lg"><span>{{ opt
                        }}. </span>{{ exams.options[curIdx]?.[opt] }}</p>
                    </el-radio>
                </template>
            </el-radio-group>
        </template>
        <template v-else>
            <template v-for="opt in optArr">
                <el-checkbox-group v-model="selOptArr" v-if="exams.options[curIdx]?.[opt]">
                    <el-checkbox :label="opt" border size="large" class="w-full">
                        <p class="text-lg"><span>{{ opt }}. </span>{{ exams.options[curIdx]?.[opt] }} <span>{{
                            exams.options[curIdx].answer }}</span></p>
                    </el-checkbox>
                </el-checkbox-group>
            </template>
        </template>
        <div class="flex [&_button]:flex-1">
            <el-button type="primary" :disabled="curIdx < 1" plain @click="prev" size="large">上一题</el-button>
            <el-button type="primary" :disabled="(curExam.answer?.length!==1&&selOptArr?.length==0)||(curExam.answer?.length==1&&!selOpt)" block @click="next" size="large">{{ curIdx
                + 1 ==
                exams.options?.length ? '提交答卷' :
                '下一题'
            }}</el-button>
        </div>
        <p class="text-center text-slate-400 leading-relaxed">甘肃省司法厅&copy;版权所有<br>中国甘肃网技术支持</p>
    </div>
</template>

<script setup>
import { computed } from 'vue';

const router = useRouter()
const route = useRoute()

// 确认环节
let timer = ref(null)
let limit = ref(null)
const ruleFormRef = ref(null)
const userForm = ref({
    nickname: null,
    company: null,
    phone: null,
})
const agree = ref(false)
const validateNickname = (rule, value, callback) => {
    let nameReg = /^[\u4e00-\u9fa5]{2,10}$/
    if (!nameReg.test(value)) return callback(new Error('姓名必须是汉字，长度为2-10'))
    callback()
}

const validatePhone = (rule, value, callback) => {
    let phoneReg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (!phoneReg.test(value)) return callback(new Error('手机号填写错误'))
    callback()
}
const rules = reactive({
    nickname: [{ required: true, message: '姓名为必填', trigger: 'blur' }, { validator: validateNickname, trigger: 'blur' }],
    phone: [{ required: true, message: '手机号为必填', trigger: 'blur' }, { validator: validatePhone, trigger: 'blur' }],
})
const agreeHandler = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            agree.value = true
            limit.value = exams.value.topic.limit
            timer.value = setInterval(() => {
                limit.value--
                if (limit.value <= 0) {
                    clearInterval(timer.value)
                    curIdx.value = exams.value.options?.length - 1
                    next();
                }
            }, 1000)
            return true
        } else {
            return false
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
// 答题环节
const optArr = ref(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'])
const curIdx = ref(0)
const curExam = computed(()=>exams.value.options[curIdx.value])
const selOpt = ref('')
const selOptArr = ref([])
const { data: exams } = await useFetch(`/api/chouti`, { method: 'post', body: { topic: route.params?.id } })
watch(curIdx, () => {
    selOpt.value = exams.value.options[curIdx.value].answer?.length==1 ? exams.value.options[curIdx.value]?.selected : ''
    selOptArr.value = exams.value.options[curIdx.value].answer?.length!=1 ? exams.value.options[curIdx.value]?.selected?.split('') : []
})
const prev = () => {
    if (curIdx.value > 0) curIdx.value--
}

const next = async () => {
    exams.value.options[curIdx.value].answer = exams.value.options[curIdx.value].answer?.split('')?.sort().join('').toUpperCase()
    if (exams.value.options[curIdx.value].answer?.length == 1) {
        exams.value.options[curIdx.value].selected = selOpt.value?.toUpperCase()
    } else {
        exams.value.options[curIdx.value].selected = selOptArr.value?.sort().join('').toUpperCase()
    }
    if (curIdx.value + 1 >= exams.value.options?.length) {
        const success = exams.value.options.filter(x => x.answer == x.selected)
        const score = success.length * (100 / exams.value.options?.length)
        const { data: history } = await useFetch(`/api/history`, { method: 'post', body: { user: userForm, score, content: JSON.stringify(exams.value.options), topicId: route.params?.id, speed: exams.value.topic.limit - limit.value } })
        return router.replace({ path: '/answer/success', query: { score: history.value.score, topic: history.value.topicId, user: userForm.value.nickname, title: exams.value.topic.title, userId: history.value.userId, postId: history.value.id } })
    }
    // 更新显示题目
    curIdx.value++
}

onBeforeUnmount(() => {
    clearInterval(timer)
    timer = null
})
</script>

<style scoped>.el-radio,
.el-checkbox-group {
    margin: 15px;
}</style>